package com.sos.config;

import com.sos.util.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    private final JwtUtils jwtUtils;

    public JwtAuthenticationFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            // 对于/api/files/**路径，跳过JWT验证
            String requestURI = request.getRequestURI();
            logger.info("Processing request URI: {}", requestURI);
            
            // 1. 提取Authorization头
            String authHeader = request.getHeader("Authorization");
            String token = null;
            String username = null;

            // 2. 校验头格式并提取Token、用户名
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
                // 只有当token非空时才尝试解析用户名
                if (token != null && !token.isEmpty()) {
                    username = jwtUtils.getUsernameFromToken(token);
                }
            }

            // 3. 清除残留的认证信息（关键：无论Token是否有效，先重置上下文）
            SecurityContextHolder.clearContext();

            // 4. 若Token有效，设置新的认证信息
            if (username != null && !username.isEmpty() && token != null && !token.isEmpty() && jwtUtils.isTokenValid(token)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username,
                        null,
                        Collections.emptyList()
                );
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            logger.error("JWT Token解析失败：", e);
            // 异常时强制清除上下文
            SecurityContextHolder.clearContext();
        }

        // 继续执行后续过滤器
        filterChain.doFilter(request, response);

        // 关键：请求处理完毕后，彻底清除上下文（防止线程复用导致信息残留）
        SecurityContextHolder.clearContext();
    }
}